package com.sparrow.rpc.manager;

import com.sparrow.rpc.domain.RpcNode;
import com.sparrow.rpc.socket.RpcClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class RpcClientManager implements DisposableBean {
    private static Logger logger = LoggerFactory.getLogger(RpcClientManager.class);

    private final ConcurrentHashMap<String, RpcClient> clientMap = new ConcurrentHashMap<>();

    @Autowired
    RpcNodeManager rpcNodeManager;

    public ConcurrentHashMap<String, RpcClient> getClientMap() {
        return clientMap;
    }

    /**
     * 根据节点 ID 获取 RpcClient 实例
     *
     * @param nodeId 节点 ID
     * @return RpcClient 实例
     */
    public RpcClient getRpcClient(String nodeId) {
        RpcNode node = rpcNodeManager.getNode(nodeId);
        if (node == null) {
            return null;
        }
        return clientMap.computeIfAbsent(nodeId, k -> new RpcClient(node.getId(), node.getIp(), node.getPort()));
    }

    public RpcClient removeRpcClient(String nodeId) {
        RpcClient remove = clientMap.remove(nodeId);
        if (remove != null) {
            remove.shutdown();
            logger.info("移除rpcClient {}", nodeId);
        }
        return remove;
    }

    /**
     * 检查客户端连接状态
     */
    public boolean isConnected(String nodeId) {
        RpcClient client = clientMap.get(nodeId);
        return client != null && client.isActive(); // 需要在RpcClient中添加isActive方法
    }

    @Override
    public void destroy() throws Exception {
        for (RpcClient client : clientMap.values()) {
            client.shutdown();
        }
        RpcClient.group.shutdownGracefully().get();
        logger.info("RpcClient关闭");
    }
}
